package com.ygl.consumer.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.ygl.consumer.lb.MyLoadBalance;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @Author yanggld
 * @Date 2019/11/21-11:25
 * @Description
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RestController
public class LoadBalanceController {

	private final MyLoadBalance myLoadBalance;

	/**
	 * 这个restTemplate使用了Ribbon
	 */
	private final RestTemplate restTemplate;

	/**
	 * 通过自定义负载均衡器，实现服务间调用
	 * @return
	 */
	@GetMapping("/restByMyLoadBalance")
	@SentinelResource("myLB")
	public String restByMyLoadBalance(){
		String uri = myLoadBalance.randomGetUri("service-provider");
		RestTemplate restTemplate = new RestTemplate();
		String url = uri + "/test/name";
		ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class, "");
		String body = entity.getBody();
		return body;
	}

	/**
	 * 通过ribbon进行负载均衡，实现服务间调用
	 * @return
	 */
	@GetMapping("/restByRibbon")
	public String restByRibbon(){
		long start = System.currentTimeMillis();
		String url = "http://service-provider/test/name";
		ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class, "");
		String body = entity.getBody();
		long end = System.currentTimeMillis();
		log.info("请求的时间:{}",(end-start));
		return body;
	}


}
